import { message } from 'antd'
import { createContext, useContext } from 'react'

// 创建Context用于传递messageApi和contextHolder
const AppMessageContext = createContext()

const useAppMessage = () => {
  const [messageApi, contextHolder] = message.useMessage()

  const AppMessageProvider = ({ children }) => {
    return (
      // 使用正确的Context Provider
      <AppMessageContext.Provider value={{ messageApi, contextHolder }}>
        {contextHolder}
        {children}
      </AppMessageContext.Provider>
    )
  }

  return {
    AppMessageProvider,
  }
}

// 提供一个自定义hook用于在组件中获取messageApi
export const useMessage = () => {
  const context = useContext(AppMessageContext)
  if (!context) {
    throw new Error('useMessage must be used within AppMessageProvider')
  }
  return context.messageApi
}

export default useAppMessage
